package imager;

import clases.CustomImageIcon;
import clases.ModelTableCliente;
import coneccion.ConexionBase;
import controller.ControllerCliente;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import model.Cliente;

/**
 *
 * @author El APRENDIZ www.elaprendiz.net63.net
 */
public class LeerClientes extends javax.swing.JFrame {

    /**
     * Creates new form LeerClientes
     */
    public String id;
    private FileInputStream fis;
    private int longitudBytes;
    private ControllerCliente cc;
    private Cliente cl;
    public LeerClientes() {
        initComponents();  
        cc = new ControllerCliente();
        this.setLocationRelativeTo(null);
        jTable1.setModel(new ModelTableCliente(cc.getClientes()));
        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

            @Override
            public void valueChanged(ListSelectionEvent e) {
               if(jTable1.getSelectedRow() != -1)
               {
                   int fila = jTable1.getSelectedRow();
                   cl = ((ModelTableCliente)jTable1.getModel()).getFila(fila);
                   id = jTable1.getValueAt(fila, 0).toString();
                   txtNombre.setText(cl.getNombre());
                   txtApellido.setText(cl.getApelldos());
                   txtEmail.setText(cl.getEmail());
                   cbEstado.setSelectedItem(cl.getEstadoCuenta());
                    CustomImageIcon foto = ConexionBase.getFoto(Integer.parseInt(id));
                    if(foto!=null)
                    {
                       lbFoto.setIcon(foto);
                    }else{
                     lbFoto.setIcon(new CustomImageIcon(getClass().getResource("/resource/defaultlarge.gif")));
                    }
                    lbFoto.updateUI();
               }
            }
        });
    }

   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtApellido = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cbEstado = new javax.swing.JComboBox();
        bntGrabar = new javax.swing.JButton();
        bntActualizar = new javax.swing.JButton();
        lbFoto = new javax.swing.JLabel();
        bntNuevo = new javax.swing.JButton();
        bntEliminar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 4, 0);
        jPanel1.add(jButton1, gridBagConstraints);

        jLabel1.setText("Nombre:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        jPanel1.add(jLabel1, gridBagConstraints);

        txtNombre.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(7, 8, 0, 0);
        jPanel1.add(txtNombre, gridBagConstraints);

        jLabel2.setText("Apellido:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        jPanel1.add(jLabel2, gridBagConstraints);

        txtApellido.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(7, 8, 0, 0);
        jPanel1.add(txtApellido, gridBagConstraints);

        jLabel3.setText("Email:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        jPanel1.add(jLabel3, gridBagConstraints);

        txtEmail.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(7, 8, 0, 0);
        jPanel1.add(txtEmail, gridBagConstraints);

        jLabel4.setText("Estado de Cuenta:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        jPanel1.add(jLabel4, gridBagConstraints);

        cbEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Debe", "No Debe" }));
        cbEstado.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(7, 8, 0, 0);
        jPanel1.add(cbEstado, gridBagConstraints);

        bntGrabar.setText("Grabar");
        bntGrabar.setEnabled(false);
        bntGrabar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntGrabarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 4, 0);
        jPanel1.add(bntGrabar, gridBagConstraints);

        bntActualizar.setText("Actualizar");
        bntActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntActualizarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 4, 0);
        jPanel1.add(bntActualizar, gridBagConstraints);

        lbFoto.setBackground(new java.awt.Color(0, 153, 255));
        lbFoto.setIcon(new CustomImageIcon(getClass().getResource("/resource/defaultlarge.gif")));
        lbFoto.setPreferredSize(new java.awt.Dimension(100, 80));
        lbFoto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbFotoMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.gridheight = 4;
        jPanel1.add(lbFoto, gridBagConstraints);

        bntNuevo.setText("Nuevo");
        bntNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntNuevoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 4, 0);
        jPanel1.add(bntNuevo, gridBagConstraints);

        bntEliminar.setText("Eliminar");
        bntEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntEliminarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 4, 0);
        jPanel1.add(bntEliminar, gridBagConstraints);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setPreferredSize(new java.awt.Dimension(375, 200));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.txtNombre.setText("");
        this.txtApellido.setText("");
        this.txtEmail.setText("");
        this.cbEstado.setSelectedIndex(0);
        lbFoto.setIcon(new CustomImageIcon(getClass().getResource("/resource/defaultlarge.gif")));
        this.fis = null;
        this.longitudBytes = 0;
        cl = null;
        this.bntGrabar.setEnabled(false);
        bntNuevo.setEnabled(true);
        this.jTable1.clearSelection();
        this.bntActualizar.setEnabled(true);
        this.bntEliminar.setEnabled(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void bntGrabarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntGrabarActionPerformed
        if(this.txtNombre.getText().isEmpty() 
           || this.txtApellido.getText().isEmpty()
           || this.txtEmail.getText().isEmpty()
           || this.cbEstado.getSelectedIndex() == -1)
        {
            JOptionPane.showMessageDialog(this, "Todos los campos son "
                    + "obligatorios, exepto la foto");
            return;
        }

        boolean emailEncontrado = ConexionBase.existeEmail(this.txtEmail.getText());
        if(emailEncontrado)
        {
           JOptionPane.showMessageDialog(this, "el email "+this.txtEmail.getText()
                    + " ya existe ingrese otro email");
            return; 
        }
        Cliente cl = new Cliente();
        cl.setNombre(txtNombre.getText());
        cl.setApelldos(txtApellido.getText());
        cl.setEmail(txtEmail.getText());
        cl.setEstadoCuenta(cbEstado.getSelectedItem().toString());
        cl.setFoto(fis);
        int opcion = cc.insertCliente(cl);
        
         if(opcion != 0)
         {
            try {
                JOptionPane.showMessageDialog(this, "Registro "+cl+" agregado");
                jTable1.setModel(new ModelTableCliente(cc.getClientes()));
                this.bntGrabar.setEnabled(false);
                bntNuevo.setEnabled(true);
                 this.bntActualizar.setEnabled(true);
                 this.bntEliminar.setEnabled(true);
                 if(fis != null)
                    fis.close();
                 fis = null;
            } catch (IOException ex) {
                Logger.getLogger(LeerClientes.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
    }//GEN-LAST:event_bntGrabarActionPerformed

private void bntActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntActualizarActionPerformed
   if(cl != null)
   {
    cl.setNombre(txtNombre.getText());
    cl.setApelldos(txtApellido.getText());
    cl.setEmail(txtEmail.getText());
    cl.setEstadoCuenta(cbEstado.getSelectedItem().toString());
    cl.setFoto(fis);
    int opcion = cc.actualzartCliente(cl);
         if(opcion != 0)
         {
              JOptionPane.showMessageDialog(this, "Registro Actualizado");
              jTable1.setModel(new ModelTableCliente(cc.getClientes()));
               if(fis != null)
               {
                   try {
                        fis.close();
                    } catch (IOException ex) {
                        Logger.getLogger(LeerClientes.class.getName()).log(Level.SEVERE, null, ex);
                    }
               }
                 fis = null;
         }
   }else{
       JOptionPane.showMessageDialog(this, "Primero seleccione un Cliente");
   }
  
    
}//GEN-LAST:event_bntActualizarActionPerformed

    private void lbFotoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbFotoMouseClicked
        JFileChooser se = new JFileChooser();
        se.setFileSelectionMode(JFileChooser.FILES_ONLY);       
        int estado = se.showOpenDialog(null);
        if(estado == JFileChooser.APPROVE_OPTION)
        {
            try {
                
                fis =  new FileInputStream(se.getSelectedFile());
                this.longitudBytes = (int)se.getSelectedFile().length();
                
                Image icono = ImageIO.read(se.getSelectedFile()).getScaledInstance(lbFoto.getWidth(), lbFoto.getHeight(), Image.SCALE_DEFAULT);
                lbFoto.setIcon(new ImageIcon(icono));
                lbFoto.updateUI(); 
                
            } catch (FileNotFoundException ex) {ex.printStackTrace();}
            catch (IOException ex){ex.printStackTrace();}
        }
    }//GEN-LAST:event_lbFotoMouseClicked

    private void bntNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntNuevoActionPerformed
        this.txtNombre.setText("");
        this.txtApellido.setText("");
        this.txtEmail.setText("");
        this.cbEstado.setSelectedIndex(0);
        lbFoto.setIcon(new CustomImageIcon(getClass().getResource("/resource/defaultlarge.gif")));
        this.fis = null;
        this.longitudBytes = 0;
        this.bntGrabar.setEnabled(true);
        bntNuevo.setEnabled(false);
        this.bntActualizar.setEnabled(false);
        this.bntEliminar.setEnabled(false);
        cl = null;       
        this.jTable1.clearSelection();       
    }//GEN-LAST:event_bntNuevoActionPerformed

    private void bntEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntEliminarActionPerformed
        if(cl != null)
        {
            int eliminarCliente = cc.eliminarCliente(cl.getPrimaryKey());
            if(eliminarCliente != 0)
             {
                  JOptionPane.showMessageDialog(this, "Registro Eliminado");
                  jTable1.setModel(new ModelTableCliente(cc.getClientes()));
             }
        }else
        {
            JOptionPane.showMessageDialog(this, "Primero seleccione un cliente");
        }
        
    }//GEN-LAST:event_bntEliminarActionPerformed

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntActualizar;
    private javax.swing.JButton bntEliminar;
    private javax.swing.JButton bntGrabar;
    private javax.swing.JButton bntNuevo;
    private javax.swing.JComboBox cbEstado;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbFoto;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
